package school.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import school.domain.Article;
import school.domain.User;
import school.mapper.ArticleMapper;
import school.mapper.UserMapper;
import school.support.BaseController;

import java.util.Date;

@RequestMapping("article")
@Controller
public class ArticleController extends BaseController {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserMapper userMapper;

    @GetMapping("send")
    public String send() {
        return "add";
    }

    /**
     * 发布文章
     * @param article
     * @param icon
     * @return
     */
    @PostMapping("send")
    public String send(Article article, MultipartFile icon) {
        article.setAddtime(new Date());
        article.setUserid(frontUser().getId());
        article.setImg(saveFile(icon));
        articleMapper.insertSelective(article);

        User user = userMapper.selectByPrimaryKey(frontUser().getId());
        user.setArticlenum(user.getArticlenum()+1);
        userMapper.updateByPrimaryKeySelective(user);

        session.setAttribute("errorMsg", "发布成功");
        return "redirect:/index";
    }
}
